package com.mm.fam.web.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mm.fam.RtConstant;
import com.mm.fam.pb.CoreEnum.ConnectStatusEnum;
import com.mm.fam.pb.CoreEnum.GatewayAdapterTypeEnum;
import com.mm.fam.pb.CoreEnum.GatewayTypeEnum;
import com.mm.fam.web.entity.CtpSetting;
import com.mm.fam.web.entity.Gateway;
import com.mm.fam.web.mapper.CtpSettingMapper;
import com.mm.fam.web.mapper.GatewayMapper;
import com.mm.fam.web.mapper.NodeMapper;
import com.mm.fam.web.service.GatewayService;
import com.mm.fam.web.service.MasterTradeCachesService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GatewayServiceImpl extends ServiceImpl<GatewayMapper, Gateway> implements GatewayService, InitializingBean {

	private static Logger logger = LoggerFactory.getLogger(GatewayServiceImpl.class);

	@Autowired
	private GatewayMapper gatewayMapper;

	@Autowired
	private CtpSettingMapper ctpSettingMapper;

	@Autowired
	private NodeMapper nodeMapper;
	@Autowired
	private MasterTradeCachesService masterTradeCachesService;

//	private ScheduledExecutorService scheduledExecutorService = newSingleThreadScheduledExecutor();

	@Override
	public void afterPropertiesSet() throws Exception {
//		scheduledExecutorService.scheduleAtFixedRate(() -> {
//			try {
//				List<Node> nodeList = nodeMapper.selectList(null);
//				Map<Integer, Node> nodeMap = new HashMap<>();
//
//				for (Node node : nodeList) {
//					nodeMap.put(node.getNodeId(), node);
//				}
//
//				List<Gateway> gatewayList = gatewayMapper.selectList(new Gateway());
//
//				for (Gateway gateway : gatewayList) {
//					if (gateway.getStatus() == ConnectStatusEnum.CONNECTED_VALUE) {
//						if (!nodeMap.containsKey(gateway.getTargetNodeId())
//								|| nodeMap.get(gateway.getTargetNodeId()).getStatus() != Node.NODE_STATUS_CONNECTED) {
//							gateway.setStatus(ConnectStatusEnum.CONNECTING_VALUE);
//							gatewayMapper.updateById(gateway);
//						}
//					}
//
//				}
//			} catch (Exception e) {
//				logger.error("定时检查网关状态异常", e);
//			}
//
//		}, 5, 5, TimeUnit.SECONDS);

	}

	@Override
	public Gateway getGatewayByGatewayId(String gatewayId) {
		if (StringUtils.isBlank(gatewayId)) {
			logger.error("根据网关ID获取网关错误,参数gatewayId缺失");
			throw new IllegalArgumentException("根据网关ID获取网关错误,参数gatewayId缺失");
		}
		return gatewayMapper.selectById(gatewayId);
	}

	@Override
	public List<Gateway> getGatewayList() {
		return gatewayMapper.selectList(new Gateway());
	}

	@Override
	public void upsertGatewayByGatewayId(Gateway gateway) {
		if (gateway == null) {
			logger.error("根据网关ID更新或保存网关错误,参数gateway缺失");
			throw new IllegalArgumentException("根据网关ID更新或保存网关错误,参数gateway缺失");
		}
		// 新增网关
		if(gateway.getGatewayId() == null){
//			CtpSetting ctpSetting = gateway.getCtpSetting();
//			ctpSettingMapper.insert(ctpSetting);
//			gateway.setCtpSetting(ctpSetting);
			gatewayMapper.insert(gateway);
			return;
		}
		if (StringUtils.isBlank(gateway.getGatewayId().toString())) {
			logger.error("根据网关ID更新或保存网关错误,参数gatewayId缺失");
			throw new IllegalArgumentException("根据网关ID更新或保存网关错误,参数gatewayId缺失");
		}

		if (gateway.getGatewayAdapterType() == null) {
			gateway.setGatewayAdapterType(GatewayAdapterTypeEnum.CTP_VALUE);
		}
		if (gateway.getGatewayDescription() == null) {
			gateway.setGatewayDescription("");
		}
		if (gateway.getGatewayName() == null) {
			gateway.setGatewayName("");
		}

		if (gateway.getGatewayType() == null) {
			gateway.setGatewayType(GatewayTypeEnum.TRADE_AND_MARKET_DATA_VALUE);
		}

		if (gateway.getImplementClassName() == null) {
			gateway.setImplementClassName("");
		}

		if (gateway.getStatus() == null) {
			gateway.setStatus(ConnectStatusEnum.DISCONNECTED_VALUE);
		}

		if (gateway.getTargetNodeId() == null) {
			gateway.setTargetNodeId(0);
		}
		if (gateway.getVersion() == null) {
			gateway.setVersion(System.currentTimeMillis());
		}

		Gateway dbGateway = gatewayMapper.selectById(gateway.getGatewayId());

		if (dbGateway != null) {
			if (dbGateway.getCtpSetting() != null && gateway.getCtpSetting() != null) {
				if (RtConstant.SECURITY_MASK.equals(gateway.getCtpSetting().getAuthCode())) {
					gateway.getCtpSetting().setAuthCode(dbGateway.getCtpSetting().getAuthCode());
				}
				if (RtConstant.SECURITY_MASK.equals(gateway.getCtpSetting().getPassword())) {
					gateway.getCtpSetting().setPassword(dbGateway.getCtpSetting().getPassword());
				}
			}
		}

		gatewayMapper.updateById(gateway);
	}

	@Override
	public void deleteGatewayByGatewayId(String gatewayId) {
		if (StringUtils.isBlank(gatewayId)) {
			logger.error("根据网关ID删除网关错误,参数gatewayId缺失");
			throw new IllegalArgumentException("根据网关ID删除网关错误,参数gatewayId缺失");
		}
		gatewayMapper.deleteById(gatewayId);
		masterTradeCachesService.clearAllCachesByGatewayId(gatewayId);
	}

	@Override
	public void connectGatewayByGatewayId(String gatewayId) {
		if (StringUtils.isBlank(gatewayId)) {
			logger.error("根据网关ID连接网关错误,参数gatewayId缺失");
			throw new IllegalArgumentException("根据网关ID连接网关错误,参数gatewayId缺失");
		}

		Gateway gateway = getGatewayByGatewayId(gatewayId);
		if (gateway == null) {
			logger.warn("根据网关ID连接网关,未找到网关记录,网关ID:{}", gatewayId);
			return;
		}
		if (gateway.getStatus() == ConnectStatusEnum.DISCONNECTING_VALUE || gateway.getStatus() == ConnectStatusEnum.DISCONNECTED_VALUE
				|| gateway.getStatus() == null) {
			gateway.setStatus(ConnectStatusEnum.CONNECTING_VALUE);
			upsertGatewayByGatewayId(gateway);
		} else {
			logger.info("根据网关ID连接网关,当前状态无需更改,网关ID:{},状态码:{}", gateway.getGatewayId(), gateway.getStatus());
		}
	}

	@Override
	public void disconnectGatewayByGatewayId(String gatewayId) {
		if (StringUtils.isBlank(gatewayId)) {
			logger.error("根据网关ID断开网关错误,参数gatewayId缺失");
			throw new IllegalArgumentException("根据网关ID断开网关错误,参数gatewayId缺失");
		}
		Gateway gateway = getGatewayByGatewayId(gatewayId);
		if (gateway == null) {
			logger.warn("根据网关ID断开网关,未找到网关记录,网关ID:{}", gatewayId);
			return;
		}
		if (gateway.getStatus() == ConnectStatusEnum.CONNECTING_VALUE || gateway.getStatus() == ConnectStatusEnum.CONNECTED_VALUE
				|| gateway.getStatus() == null) {
			gateway.setStatus(ConnectStatusEnum.DISCONNECTING_VALUE);
			upsertGatewayByGatewayId(gateway);
		} else {
			logger.info("根据网关ID断开网关,当前状态无需更改,网关ID:{},状态码:{}", gateway.getGatewayId(), gateway.getStatus());
		}
		masterTradeCachesService.clearAllCachesByGatewayId(gatewayId);
	}

	@Override
	public void disconnectAllGateways() {
		List<Gateway> gatewayList = gatewayMapper.selectList(new Gateway());
		for (Gateway gateway : gatewayList) {
			if (gateway.getStatus() == ConnectStatusEnum.CONNECTING_VALUE || gateway.getStatus() == ConnectStatusEnum.CONNECTED_VALUE
					|| gateway.getStatus() == null) {
				gateway.setStatus(ConnectStatusEnum.DISCONNECTING_VALUE);
				upsertGatewayByGatewayId(gateway);
			} else {
				logger.info("断开全部网关,当前状态无需更改,网关ID:{},状态码:{}", gateway.getGatewayId(), gateway.getStatus());
			}
			masterTradeCachesService.clearAllCachesByGatewayId(gateway.getGatewayId().toString());
		}
	}

	@Override
	public void connectAllGateways() {
		List<Gateway> gatewayList = gatewayMapper.selectList(new Gateway());
		for (Gateway gateway : gatewayList) {
			if (gateway.getStatus() == ConnectStatusEnum.DISCONNECTING_VALUE || gateway.getStatus() == ConnectStatusEnum.DISCONNECTED_VALUE
					|| gateway.getStatus() == null) {
				gateway.setStatus(ConnectStatusEnum.CONNECTING_VALUE);
				upsertGatewayByGatewayId(gateway);
			} else {
				logger.info("连接全部网关,当前状态无需更改,网关ID:{},状态码:{}", gateway.getGatewayId(), gateway.getStatus());
			}
			masterTradeCachesService.clearAllCachesByGatewayId(gateway.getGatewayId().toString());
		}
	}
}
